package com.example.demo02.controller;

import cn.hutool.core.util.StrUtil;
import com.example.demo02.common.AuthAccess;
import com.example.demo02.common.Result;
import com.example.demo02.entity.Employee;
import com.example.demo02.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;


@Slf4j
@RestController
public class WebController {

    @Resource
    EmployeeService employeeService; Employee  employee;


    @GetMapping("/")
    public Result hello() {
        return Result.success("success");
    }


    @PostMapping("/login")
    public Result login(@RequestBody Employee employee) {
        if (StrUtil.isBlank(employee.getUsername()) || StrUtil.isBlank(employee.getPassword())) {
            return Result.error("数据输入不合法");
        }
        employee = employeeService.login(employee);
        return Result.success(employee);
    }

    @AuthAccess
    @PostMapping("/register")
    public Result register(@RequestBody Employee employee) {
        if (StrUtil.isBlank(employee.getUsername()) || StrUtil.isBlank(employee.getPassword())) {
            return Result.error("用户名或密码不能为空");
        }
        if (employee.getUsername().length() > 10 || employee.getPassword().length() > 20) {
            return Result.error("用户名或密码长度超出限制");
        }
        if (StrUtil.isBlank(employee.getPosition())) {
            employee.setPosition("普通"); // 设置默认职位
        }
        if (employee.getHireDate() == null) {
            employee.setHireDate(new Date()); // 设置默认日期为当前日期
        }
        if (employee.getSalary() == null) {
            employee.setSalary(3000.0); // 设置默认钱
        }

        Employee registeredEmp = employeeService.register(employee);
        if (registeredEmp != null) {
            // 注册成功，返回成功结果
            return Result.success(registeredEmp);
        } else {
            // 注册失败，返回错误信息
            return Result.error("注册失败，请重试");
        }
    }
    /**
     *  Controller重置密码
     */

    @AuthAccess
    @PutMapping("/password")
    public Result password(@RequestBody Employee employee) {
        if (StrUtil.isBlank(employee.getUsername()) || StrUtil.isBlank(employee.getPhone())) {
            return Result.error("数据输入不合法");
        }
        employeeService.resetPassword(employee);
        return Result.success();
    }

}
